package wonder.console;

import java.io.Console;
import java.util.List;

import wonder.Board;
import wonder.ISWService;
import wonder.ISWService.BoardSet;
import wonder.ISWService.BoardSide;
import wonder.SWServiceFactory;
import wonder.tools.LoggerHelper;

public enum Command {
	BYE(new Action() {
		@Override
		public void exec(Console c, List<String> params) {
			exit(c);
		}
	}), EXIT(new Action() {
		@Override
		public void exec(Console c, List<String> params) {
			exit(c);
		}
	}), SETS(new Action() {
		@Override
		public void exec(Console c, List<String> params) throws Exception {
			ISWService swm = SWServiceFactory.getInstance().getSWService();
			List<BoardSet> rc = swm.getSetList();
			c.printf("Sets: #" + rc.size() + " " + rc + "%n");
		}
	}), WONDER(new Action() {
		@Override
		public void exec(Console c, List<String> params) throws Exception {
			ISWService swm = SWServiceFactory.getInstance().getSWService();

			if (params.size() > 1) {
				String wonder = params.get(0).toUpperCase();
				String side = params.get(1).toUpperCase();
				Board b = swm.getBoard(wonder, BoardSide.valueOf(side));
				c.printf("Wonder." + side + ": " + b + "%n");
			} else if (params.size() > 0) {
				String wonder = params.get(0).toUpperCase();
				Board b = swm.getBoard(wonder, BoardSide.A);
				c.printf("Wonder.A: " + b + "%n");
				b = swm.getBoard(wonder, BoardSide.B);
				c.printf("Wonder.B: " + b + "%n");
			} else {
				c.printf("Usage: wonder name [A|B]%n");
			}
		}
	});

	private interface Action {
		public void exec(Console c, List<String> params) throws Exception;
	}

	public interface Listener {
		public void exception(Exception e);
	}

	private Action action;

	private Command(Action a) {
		this.action = a;
	}

	public void exec(final Console c, final List<String> params,
			final Listener l) {
		try {
			action.exec(c, params);
		} catch (Exception e) {
			l.exception(e);
		}
	}

	private static void exit(Console c) {
		try {
			SWServiceFactory.getInstance().releaseSWService();
		} catch (Exception e) {
			c.printf(LoggerHelper.getStackTrace(e) + "%n");
		}
		c.printf("Bye%n");
		System.exit(0);
	}
}
